/* eslint-disable camelcase */
<template>
  <div id="gisMap">
    <div class="visual_chart" id="map"></div>
    <div class="visual_control">
      <el-button type="primary" @click="screen()" style="margin-bottom: 10px">
        <i class="iconfont icon-quanping" style="width: 100%"></i>
      </el-button>
      <!-- <el-button
        v-show="bottomModeMapView.checkedSpeciallist.length > 0"
        type="primary"
        @click="openChangeLayerWindow($event)"
      >
        <i class="iconfont icon-layer" style="width: 100%"></i>
      </el-button>
      <div id="popover_my" v-show="isShowLayer">
        <el-checkbox-group v-model="Showlayerlist" @change="changeLayerZindex">
          <el-checkbox
            v-for="(i, z) in bottomModeMapView.checkedSpeciallist"
            :key="z"
            :label="i.LId"
            >{{ i.name }}</el-checkbox
          >
        </el-checkbox-group>
        <div class="popper__arrow"></div>
      </div> -->
    </div>
  </div>
</template>

<script>
import '../styles/map.less';
import {
  mapGetters,
} from "vuex";
import storeData from "./../../../tools/vuex-store";
// import "@panzhiyue/leaflet-canvasmarker"
// import "leaflet-canvas-marker";
import 'leaflet-canvas-marker-xrr2021';
export default {
  data() {
    return {
      map: null,
      pointObj: {},
      selectedState: {}, //已经选择的区域
      viewSpotLayer: null,
      longLatList: [],
      fourPosition: {},
      rangeLevel: {
        '国家': [1, 2, 3],
        '省': [4, 5, 6],
        '市': [7, 8, 9],
        '区': [10, 11, 12],
        '街道': [13, 14, 15],
      },
      fullscreen: false,
      nowZoom: {
        level: 5,
        type: '国家'
      },
      rangeLevelPoints: {},
      tangelevelPath: [], //标记点间关系
      layerAll: {},//全部图层
      Showlayerlist: [],//显示的图层数组
      isShowLayer: false,
      ciLayer: null,
      heatmapLayer:null,//热力图
    }
  },
  mounted() {
    // setTimeout(() => {
    //     this.drawMap();
    // }, 1000)

  },
  computed: {
    ...mapGetters(["globalCountrySetting", "bottomModeMapView", "centralModeMapSetting"]),
  },
  methods: {
    //放大全屏展示地图
    screen() {
      // let element = document.documentElement;//设置后就是我们平时的整个页面全屏效果
      let element = document.getElementById('gisMap');//设置后就是   id==gisMap 的容器全屏
      if (this.fullscreen) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
          element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen();
        }
      }
      this.fullscreen = !this.fullscreen;
    },
    //初始化图层
    drawMap(nowCountry) {
      let index = nowCountry.id.slice(1, nowCountry.id
        .length) - 1;
      let nowtry = this.globalCountrySetting[index];
    //   let glayerSatelite = new L.TileLayer("/globle/tiles/{z}/{y}/{x}.jpg", {
    //     minZoom: 1,
    //     maxZoom: 18,
    //     attribution: "卫星地图",
    //   });
    let glayerSatelite = new L.TileLayer("/globle/tiles/imgm/{z}/{y}/{x}.jpg", {
            minZoom: 1,
            maxZoom: 9,
            attribution: "卫星地图",
    });
      // let glayerSatelite = new L.TileLayer('http://' + location.hostname + ':8081/{z}/{y}/{x}.jpg', {minZoom: 3, maxZoom: 8, attribution: '卫星地图'});

      /* 热力图 start */

      //配置
      var cfg = {
        "radius": 3,
        "maxOpacity": 0.8,
        "scaleRadius": true,
        "useLocalExtrema": true,
        latField: 'lat',
        lngField: 'lng',
        valueField: 'count'
      };
       this.heatmapLayer = new HeatmapOverlay(cfg);
      /* 热力图 start */

      // let glayerSatelite = new L.TileLayer('http://' + '192.168.1.179' + ':9880/tiles2/{z}/{y}/{x}.jpg', {
      //     minZoom: 3,
      //     maxZoom: 8,
      //     attribution: '卫星地图'
      // });
      // let glayerSatelite = new L.TileLayer('http://' + location.hostname + ':8081/{z}/{y}/{x}.jpg', {minZoom: 3, maxZoom: 8, attribution: '卫星地图'});
      let latlng = new L.LatLng(nowtry.position[0], nowtry.position[1]);
      // let latlng = new L.LatLng(31.198706347135246, 121.4813232421875);
      this.map = new L.Map("map", {
        center: latlng,
        zoom: this.nowZoom.level,
        layers: [glayerSatelite, this.heatmapLayer],
        zoomControl: false,
        Legend: true,
        attributionControl: false,
        preferCanvas: true
      });
      // console.log(this.map);
      // let baseLayers = {
      //     // "普通地图": glayerNormal,
      //     "卫星地图": glayerSatelite
      // };
      // let overlays = {
      //     "混合": glayerSatelite
      // };
      // L.control.layers(baseLayers, {position: 'topright'}).addTo(this.map);
      this.viewSpotLayer = new L.LayerGroup([]);
      this.map.addLayer(this.viewSpotLayer);
    //   this.viewSpotLayer.bringToBack()
      this.addMapEvents();
      // eslint-disable-next-line no-underscore-dangle
      //   let _this = this;
      //   //设置样式
      //   var myStyle = {
      //     "color": "#00f",
      //     "weight": 2,
      //     "opacity": 0.5,
      //     "fillColor": 'red',
      //     "fillOpacity": 0,
      //   };
      //   $.ajax("/globle/json/points.json", {
      //     dataType: "json",
      //     success: function (response) {
      //       L.geoJSON(response, {
      //         style: myStyle,
      //       }).addTo(_this.map);
      //     }
      //   });
      // this.addCustomLengda()；
      let that = this;
      //   L.Control.sreen = L.Control.extend({
      //     options: {
      //       position: 'topright' //初始位置

      //     },
      //     initialize: function (options) {
      //       L.Util.extend(this.options, options);
      //     },
      //     onAdd: function (map) {
      //       //创建一个class为leaflet-control-sreen的div
      //       this._container = L.DomUtil.create('div', 'leaflet-control-sreen');
      //       //创建一个图片要素
      //       var legendimg = document.createElement('img');
      //       legendimg.id = 'leaflet-control-sreen';
      //       legendimg.type = 'img';
      //       legendimg.src = "../../../../static/image/screen.png";
      //       this._legendimg = legendimg;
      //       //创建一个关闭控件的按钮
      //       var closebutton = document.createElement('a');
      //       closebutton.id = 'leaflet-control-geosearch-close';
      //       closebutton.className = 'glyphicon glyphicon-remove';
      //       this._closebutton = closebutton;

      //       this._container.appendChild(this._closebutton);
      //       this._container.appendChild(this._legendimg);
      //       //注册关闭事件
      //       L.DomEvent.addListener(this._closebutton, 'click', this._onCloseControl, this);
      //       //注册全屏事件
      //       L.DomEvent.addListener(this._legendimg, 'click', this._onScreen, this);

      //       return this._container;
      //     },
      //     _onCloseControl: function () {
      //       l
      //       this._map.options.Legend = false;
      //       this.removeFrom(this.map);
      //     },
      //     _onScreen: function () {
      //       console.log('000')
      //       that.screen()
      //       //  that.$emit('openSreen',true)
      //     },
      //   });
      //   L.control.sreen = function (opts) {
      //     return new L.Control.sreen(opts);
      //   }
      //   var sreen = L.control.sreen({ position: 'topright' });
      //   //添加图例
      //   sreen.addTo(this.map);
      //   that.showLayerControl()
           that.ciLayer = L.canvasIconLayer({
          collisionFlg: true
        }).addTo(this.map);
    },
    // 加载基地 --复选框勾选事件
    chooseMap(node, relationlist) {
      console.log(node);
      console.log(relationlist);
      // console.log(this.globalCountrySetting);
      // let serialNumber = node.serialNumber.toString();
      //判断如果没有坐标不展示
      if (node.position.length === 0) {
        this.$message({
          message: '警告! 该实例没有坐标',
          type: 'warning'
        });
        return;
      }
      if(node.count){
          this.DrawheatChart(node)
          return
      }
      // 重新点击删除节点
      // if (!node.checked) {
      //     this.cleanLinkAttr(node, false);
      //     this.deletePoinobj(serialNumber);
      //     return;
      // }
      //假数据
      // this.secondDrawDot(node.id, node.iconName, node.fatherName);//测试
      let nodeSetting = this.globalCountrySetting[node.fatherId.slice(1, node.fatherId.length) - 1];
      console.log(nodeSetting);

      //真实
      const $this = this;

      let dotColor = L.marker(node.position, {
        icon: L.icon({
          iconSize: [12, 12],
          iconUrl: "../../../../static/dot/" + nodeSetting.DotName,
          // shadowUrl: "leaf-shadow.png",
          // shadowSize:[41,41],
          // className: tes.className,
          // color: tes.roudColor,
        }),
      })
        //图上标记点击事件
        .on("click", function (e) {
          console.log(e);
          $this.map.panTo({
            lon: e.latlng.lng,
            lat: e.latlng.lat
          });
          $this.isResult = true;
          $this.currentNode = node;
        });

      let point = L.marker(node.position, {
        icon: L.icon({
          iconSize: nodeSetting.iconSize,
          iconUrl: "../../../../static/images/" + nodeSetting.roudicon + ".png",
        }),
      })
        .addTo(this.map)
        //图上标记点击事件
        .on("click", function (e) {
          console.log(e);
          $this.map.panTo({
            lon: e.latlng.lng,
            lat: e.latlng.lat
          });
          $this.isResult = true;
          $this.currentNode = node;
          console.log($this.currentNode);
        });
      var antPath = L.polyline.antPath;
      if (relationlist) {
        for (let index = 0; index < relationlist.length; index++) {
          const element = relationlist[index];
          let longLatList = []
          if (element.position.length > 0) {
            longLatList = [node.position, element.position];
            console.log(longLatList);
            let gPath = antPath(longLatList, {
              "paused": false, //暂停  初始化状态
              "reverse": false, //方向反转
              "delay": 1000, //延迟，数值越大效果越缓慢
              "dashArray": [10, 20], //间隔样式
              "weight": 3, //线宽
              "opacity": 0.8, //透明度
              //"color": "#0000FF",　//颜色
              //"pulseColor": "#FFFFFF"　　//块颜色
            });
            gPath.addTo(this.viewSpotLayer);
            let dotColor = L.marker(element.position, {
              icon: L.icon({
                iconSize: [12, 12],
                iconUrl: "../../../../static/dot/" + nodeSetting.DotName,
                // shadowUrl: "leaf-shadow.png",
                // shadowSize:[41,41],
                // className: tes.className,
                // color: tes.roudColor,
              }),
            })
              //图上标记点击事件
              .on("click", function (e) {
                console.log(e);
                $this.map.panTo({
                  lon: e.latlng.lng,
                  lat: e.latlng.lat
                });
                $this.isResult = true;
                $this.currentNode = node;
              });

            let point = L.marker(element.position, {
              icon: L.icon({
                iconSize: nodeSetting.iconSize,
                iconUrl: "../../../../static/images/" + nodeSetting.roudicon +
                  ".png",
                // shadowUrl: "leaf-shadow.png",
                // shadowSize:[41,41],
                // className: tes.className,
                // color: tes.color,
              }),
            })
              .addTo(this.map)
              //图上标记点击事件
              .on("click", function (e) {
                console.log(e);
                $this.map.panTo({
                  lon: e.latlng.lng,
                  lat: e.latlng.lat
                });
                $this.isResult = true;
                $this.currentNode = node;
                console.log($this.currentNode);
              });
            let nodeDetail = {};
            nodeDetail["serialNumber"] = element.serialNumber;
            nodeDetail["position"] = element["position"];
            nodeDetail["point"] = point;
            nodeDetail["dot"] = dotColor;
            nodeDetail["名称"] = element.name;
            nodeDetail["地区"] = element.fatherName;
            nodeDetail["部队"] = element.troopsForm;
            nodeDetail["Infomation"] = element;
            this.pointObj[element.serialNumber] = nodeDetail;
            // this.showCanvas(node.iconName, nodeDetail);
            this.textInitReal(nodeDetail);
          }
        }
      }
      let nodeDetail = {};
      nodeDetail["serialNumber"] = node.serialNumber;
      nodeDetail["position"] = node["position"];
      nodeDetail["point"] = point;
      nodeDetail["dot"] = dotColor;
      nodeDetail["名称"] = node.name;
      nodeDetail["地区"] = node.fatherName;
      nodeDetail["部队"] = node.troopsForm;
      nodeDetail["Infomation"] = node;
      this.pointObj[node.serialNumber] = nodeDetail;
      // this.showCanvas(node.iconName, nodeDetail);
      this.textInitReal(nodeDetail);
    },
    //文字描绘
    textInitReal(node) {
      console.log(node)
      let serialNumber = node.serialNumber.toString(),
        $this = this,
        text;
      //构建子类
      let detailHtml = `<div class="detail_html" data-num="${serialNumber}">`;
      detailHtml += `<div class="detail-bgc-content_box">`;

      let detail_left = `<ul class="detail-Top">`;
      let detail_top = `<ul class="detail-Top">`;
      // let detail_right = `<ul class="detail-right">`;
      let detail_bottom = `<ul class="detail-bottom">`;
      const rows = node;
      detail_left +=
        `<li class="animated fadeInLeft animated-delay"><p title="${rows["名称"]}">名称：<span>${rows["名称"]}</span></p></li><li class="animated fadeInLeft animated-delay"><p title="${rows["地区"]}">所属：<span>${rows["地区"]}</span></p></li><li class="animated fadeInLeft animated-delay"><p title="${rows["position"][0]}+','+${rows["position"][1]}">经纬度：<span>${rows["position"]}</span></p></li>`;
      //处理部队详细信息
      if (node["部队"]) {
        if (node["部队"].length > 0) {
          let troops = node["部队"].split(";");
          // console.log(troops);
          let troopsReal = [];
          for (const i in troops) {
            let arg = {};
            if (troops[i].indexOf(",") > -1 && troops[i] !== "") {
              let children = troops[i].split(",");
              arg.title = children[0];
              arg.children = [];
              arg.expand = true;
              for (let i = 1; i < children.length; i++) {
                let tag = {};

                if (children[i].indexOf("[") > -1) {
                  tag.title = children[i].substring(0, children[i].indexOf("["));
                  //判断是否在[ ] 中间
                  let chlist = [];
                  tag.children = [];
                  chlist = children[i]
                    .substring(children[i].indexOf("["), children[i].length)
                    .split("]");
                  chlist.forEach((t) => {
                    let atj = {};
                    if (t.length == 0) {
                      return;
                    }
                    if (t.indexOf("[") > -1) {
                      atj.title = t.substr(t.indexOf("["), t.length);
                    } else {
                      atj.title = t;
                    }
                    tag.children.push(atj);
                  });
                  arg.children.push(tag);
                } else {
                  tag.title = children[i];
                  arg.children.push(tag);
                }
              }
              troopsReal.push(arg);
            } else if (troops[i].indexOf(",") < 0 && troops[i] !== "") {
              arg.title = troops[i];
              arg.expand = false;
              console.log(troops[i]);
              troopsReal.push(arg);
            }
          }
          //添加基本信息
          for (const item of troopsReal) {
            if (item.children) {
              detail_bottom +=
                `<li class="animated fadeInLeft animated-delay"><h3 title="${item.title}">${item.title}</h3><div class="animated fadeInLeft animated-delay" style="padding: 5px 0px 5px 10px;">`;
              if (item.children) {
                // eslint-disable-next-line no-loop-func
                item.children.forEach((res) => {
                  detail_bottom +=
                    `<h4 style="width:100%;text-align:left;margin:0 0 5px 0;">${res.title}</h4>`;
                  //第三层
                  if (res.children) {
                    res.children.forEach((tes) => {
                      detail_bottom +=
                        `<h5 style="width:100%;text-align:left;margin:0 0 5px 5px;">${tes.title}</h5>`;
                    });
                  }
                });
              }
              // eslint-disable-next-line camelcase
              detail_bottom += `</div></li>`;
            } else {
              // eslint-disable-next-line camelcase
              detail_bottom +=
                `<li class="animated fadeInLeft animated-delay"><h3 title="${item.title}"><span>${item.title}</span></h3>`;
              // eslint-disable-next-line camelcase
              detail_bottom += `</li>`;
            }
          }
        }
      }

      detail_left += `</ul>`;
      detail_bottom += `</ul>`;
      detailHtml += detail_left + detail_bottom + "</div>";
      let testPosition = Object.assign([], node.position);
      var popup = L.popup().setContent(
        storeData.actions.defaultNzmodatl({
          title: "基本信息",
          html: detailHtml,
          parameter: {
            height: "450px",
            left: "-334px",
            top: "-570px",
            width: "740px",
            // margin: "100px auto",
          },
          serNum: serialNumber,
        })
      );
      text = L.marker(testPosition, {
        icon: L.divIcon({
          html: node["名称"].toString(),
          iconSize: [80, "auto"],
          className: "node-text",
          iconAnchor: [40, -20],
        }),
        riseOnHover: true,
      })
        .addTo(this.map)
        .bindPopup(popup, {
          autoClose: false,
          closeOnClick: false,
          minWidth: 742
        });

      $this.map.panTo(testPosition);
      if (this.pointObj[serialNumber].text === undefined) {
        this.pointObj[serialNumber].text = [];
      }
      this.pointObj[serialNumber].text.push(text);
      return text;
    },
    //切花国家 --转移聚焦点
    transitionCentral() {
      let index = this.centralModeMapSetting.nowCountry.id.slice(1, this.centralModeMapSetting.nowCountry.id
        .length) - 1;
      let nowtry = this.globalCountrySetting[index];
      this.map.panTo(nowtry.position);
      //   this.map_drag()
      //   console.log(this.centralModeMapSetting.nowCountry);
      //   this.getMapZoomPoints()
    },
    //加载数据点 new
    loadingDot(obj,isDel) {
      console.log(obj);

      //判断是否删除
      if (!isDel) {
           console.log(this.layerAll);
           console.log(this.ciLayer);
           this.Showlayerlist.splice(this.Showlayerlist.indexOf(obj.LId), 1)
            if (obj['类型'] == "点数据") {
                this.ciLayer.removeLayers(this.layerAll[obj.LId])
            } else if (obj['类型'] == "线数据") {
                this.Showlayerlist.splice(this.Showlayerlist.indexOf(obj.LId + '_1'), 1)
                this.ciLayer.removeLayers(this.layerAll[obj.LId])
                console.log(this.layerAll[obj.LId + '_1'])
                console.log(this.viewSpotLayer)
               this.viewSpotLayer.clearLayers();
            } else {
                this.map.removeLayer(this.layerAll[obj.LId]);
            }

        return;
      }
      
      let that = this;
      //使用canvas模式渲染marker
      // 创建图层
      // 定义Marker
      if (obj["类型"] == "点数据") {
        this.$store.dispatch("ajaxApi", {
          // this.$store.dispatch("ajax", {
          url: `/map` + obj.json,
          method: "get",
          dataType: "json",
          succeed: (response) => {
            console.log(response);
            var icon = L.icon({
              iconUrl: '/static/dot/Golddot.png',
              iconSize: [20, 18],
              iconAnchor: [10, 9]
            });
            var markers = [];
            for (let i = 0; i < response.features.length; i++) {
              let p1 = [response.features[i].geometry.coordinates[1], response.features[i].geometry.coordinates[0]];

              let marker = L.marker([response.features[i].geometry.coordinates[1], response.features[i].geometry.coordinates[0]], {
                icon: icon,
              }).bindPopup("I Am " + i);
              markers.push(marker);
            }
            // 把marker添加到图层
            that.ciLayer.addLayers(markers);
            that.layerAll[obj.LId] = markers;//通过id添加
            that.Showlayerlist.push(obj.LId);
          },
          errored: (err) => {
            console.log(err);
          }
        });
      } else if (obj["类型"] == "线数据") {
        this.$store.dispatch("ajaxApi", {
          // this.$store.dispatch("ajax", {
          url: `/map` + obj.json,
          method: "get",
          dataType: "json",
          succeed: (response) => {
            console.log(response);
            var icon = L.icon({
              iconUrl: '/static/dot/Golddot.png',
              iconSize: [20, 18],
              iconAnchor: [10, 9]
            });
            var markers = [];
             let lines = []
            for (let i = 0; i < response.length; i++) {
              let p1 = [response[i].geometry.coordinates[1], response[i].geometry.coordinates[0]];
              if (response[i].relationlist) {
                for (let s = 0; s < response[i].relationlist.length; s++) {
                  let p2 = [response[i].relationlist[s].position[1], response[i].relationlist[s].position[0]]
                  let longLatList = [p1, p2];
                  let line = L.polyline(longLatList, { color: 'blue' }).addTo(that.viewSpotLayer).bindPopup("green to red");
                  let marker = L.marker(p2, {
                    icon: icon,
                  }).bindPopup("I Am " + i);
                  markers.push(marker);
                  lines.push(line);
                }
              }

              let marker = L.marker([response[i].geometry.coordinates[1], response[i].geometry.coordinates[0]], {
                icon: icon,
              }).bindPopup("I Am " + i);
              markers.push(marker);
            }
            // 把marker添加到图层
            that.ciLayer.addLayers(markers);
            that.layerAll[obj.LId + '_1'] = lines;//通过id添加
            that.Showlayerlist.push([obj.LId + '_1']);
            that.layerAll[obj.LId] = markers;//通过id添加
            that.Showlayerlist.push(obj.LId);
          },
          errored: (err) => {
            console.log(err);
          }
        })
      } else {
        // $.ajax("/globle/json/face2.json", {
        //   dataType: "json",
        //   success: function (response) {
        //     console.log(response)
        //     var myStyle = {
        //       color: "#ff7800"
        //     };
        //     let face = L.geoJSON(response, {
        //       style: myStyle,
        //     }).addTo(that.map);

        //  that.layerAll[obj.LId] = face;//通过id添加
        //     that.Showlayerlist.push(obj.LId);
        //   }
        // });
        // return
        this.$store.dispatch("ajaxApi", {
          url: `/map` + obj.json,
          method: "get",
          dataType: "json",
          succeed: (response) => {
            console.log(response)
            //    var arr = [];
            //     var coordinates = response.features[0].geometry.coordinates[0];
            //     arr.push(coordinates);
            //     var states = [{
            //         "type": "Feature",
            //         "properties": {
            //             "NAME": "西藏自治区",
            //         },
            //         "geometry": {
            //             "type": "Polygon",
            //             "coordinates": arr
            //         }
            //     }];
            var myStyle = {
              color: "#ff7800"
            };
            // Add to layer
              let face = L.geoJSON(response, {
              style: myStyle,
            }).addTo(that.map);

         that.layerAll[obj.LId] = face;//通过id添加
            that.Showlayerlist.push(obj.LId);
          },
          errored: (err) => {
            console.log(err);
          }
        });
      }
    },
    //热力图展示
    DrawheatChart(node){
      var testData = {
        data: []
      };
      //获取热力值
    let obj = {};
    for (let a of node.attrs) {
              if (a.name == 'count') {
                obj[a.name] = a.value;
              } else if (a.name == 'lat') {
                obj[a.name] = Number(a.value);
              } else if (a.name == 'lng') {
                obj[a.name] = Number(a.value);
              }
            }
            testData.data.push(obj)
          this.heatmapLayer.setData(testData);
    },
    //打开图层列表窗口
    openChangeLayerWindow() {
        this.isShowLayer = !this.isShowLayer;
    },

    //展示图层数据
    showLayerControl() {
      let that = this;
      L.Control.layerControl = L.Control.extend({
        options: {
          position: 'topright' //初始位置
        },
        initialize: function (options) {
          L.Util.extend(this.options, options);
        },
        onAdd: function (map) {
          //创建一个class为leaflet-control-sreen的div
          this._container = L.DomUtil.create('div', 'leaflet-control-layer');
          //创建一个图片要素
          var legendimg = document.createElement('img');
          legendimg.id = 'leaflet-control-layer';
          legendimg.type = 'img';
          legendimg.src = "../../../../static/image/layercontrolMO.png";
          this._legendimg = legendimg;

          this._container.appendChild(this._legendimg);
          //注册图层事件
          L.DomEvent.addListener(this._legendimg, 'click', this._onhandler, this);

          return this._container;
        },
        _onhandler: function () {
          if (that.isShowLayer) {
            that.isShowLayer = false;
            $('#leaflet-control-layer').attr('src', '../../../../static/image/layercontrol.png')
          } else {
            $('#leaflet-control-layer').attr('src', '../../../../static/image/layercontrolMO.png')
            that.isShowLayer = true;
          }

          that.changeLayerZindex()
        },
      });
      L.control.layerControl = function (opts) {
        return new L.Control.layerControl(opts);
      }
      var layercontrol = L.control.layerControl({ position: 'topright' });
      //添加图例
      layercontrol.addTo(this.map);
    },
    //展示图例
    showCanvas(iconName, nodeDetail) {
      //判断是否为空
      if (JSON.stringify(this.selectedState) == "{}") {
        let arg = {};
        arg["state"] = nodeDetail["名称"];
        arg["iconName"] = iconName;
        this.selectedState[nodeDetail["地区"]] = arg;
        this.checkItem.push(nodeDetail["地区"]);
      } else {
        //每次勾选判断是否有这个地区
        if (!this.selectedState.hasOwnProperty(nodeDetail["地区"])) {
          let arg = {};
          arg["state"] = nodeDetail["名称"];
          arg["iconName"] = iconName;
          this.selectedState[nodeDetail["地区"]] = arg;
          this.selectedState[nodeDetail["地区"]] = arg;
          this.checkItem.push(nodeDetail["地区"]);
        }
      }
      // console.log(this.selectedState);
    },
    changeLayerZindex(val) {
      console.log(val)
      console.log(this.Showlayerlist)
    //   if (this.Showlayerlist.indexOf('face') < 0) {
    //     this.Showlayerlist.push('face')
    //     this.map.addLayer(this.layerAll['face'])
    //   } else {
    //     this.Showlayerlist.splice(this.Showlayerlist.indexOf('face'), 1)
    //     this.map.removeLayer(this.layerAll['face'])
    //   }
    },
    /* 鼠标键盘绑定事件 start */
    addMapEvents() {
      let _this = this;
      //右键事件
      this.map.on("contextmenu", (e) => {
        console.log("此处坐标：", e, e.latlng.lat + "," + e.latlng.lng);

        // const $this = this;
        // let editData = {"当前节点编号":"10410","关系描述":"到达","发生时间":"2018-09-13 08:46:11","当前节点名称":"埃塞克斯号两栖攻击舰","position":[12,68],"关系类型性质":"3","到达位置":"中东"};
        // $this.drawLine(editData);
      });
      this.map.on("click", () => {
        this.hideRightModal();
      });
      this.map.on("dragstart", () => {
        this.hideRightModal();
      });
      this.map.on("dragend", () => {
        this.hideRightModal();
        // _this.dragend();
      });
      this.map.on("zoomstart", () => {
        this.hideRightModal();
      });
      this.map.on('zoomend ', function (e) {
        _this.zoomenleevel();
      });
      this.map.on('mousemove ', function (e) {
        // console.log(e)
      });
      this.map.on("popupopen", (e) => {
        const state = e.popup._container;
        if (e.type == "popupopen") {
          let ps_dialog = $(e.popup._container).find(".ps_dialog"),
            dataNum = $(ps_dialog).find(".detail_html").attr("data-num"),
            bodyWidth = $(document.body).width() / 2,
            ps_dialogOffset = $(ps_dialog).offset();
          for (const i in this.pointObj) {
            const layer = this.pointObj[i];
            if (layer.serialNumber != dataNum) {
              for (const k of layer.text) {
                k.closePopup();
              }
            }
          }
        }
      });
    },
    hideRightModal() {
      this.rightModalShow = false;
      this.treeModal = false;
    },
    //缩放等级 切换图标
    zoomenleevel() {
      let zoom = this.map.getZoom();
      for (let key in this.rangeLevel) {
        if (this.rangeLevel[key].indexOf(zoom) > -1) {
          if (this.nowZoom.type === key) {
            return;
          }
          //   if (Object.getOwnPropertyNames(this.rangeLevelPoints).length) {
          //     for (let key in this.rangeLevelPoints) {
          //       this.map.removeLayer(this.rangeLevelPoints[key].point);
          //       delete this.rangeLevelPoints[key]
          //     }
          //   }
          //   if (this.tangelevelPath.length > 0) {
          //     for (let key in this.tangelevelPath) {
          //       this.map.removeLayer(this.tangelevelPath[key].line)
          //       this.map.removeLayer(this.tangelevelPath[key].text)
          //     }
          //   }
          //   this.map_drag()
          //   this.getMapZoomPoints()
        }
      }

      // if (zoom > 4) {
      //     for (const i in this.pointObj) {
      //         this.map.addLayer(this.pointObj[i].point);
      //         this.map.addLayer(this.pointObj[i].text[0]);
      //     }
      // } else if (zoom <= 4) {
      //     for (const i in this.pointObj) {
      //         this.map.removeLayer(this.pointObj[i].point);
      //         this.map.removeLayer(this.pointObj[i].text[0]);
      //         this.map.addLayer(this.pointObj[i].dot);
      //     }
      // }
    },
    //结束拖动 请求数据
    dragend() {
      this.map_drag();
      if (Object.getOwnPropertyNames(this.rangeLevelPoints).length > 0) {
        for (let key in this.rangeLevelPoints) {
          this.map.removeLayer(this.rangeLevelPoints[key].point);
          delete this.rangeLevelPoints[key]
        }
      }
      if (this.tangelevelPath.length > 0) {
        for (let key in this.tangelevelPath) {
          this.map.removeLayer(this.tangelevelPath[key].line)
          this.map.removeLayer(this.tangelevelPath[key].text)
        }
      }
      this.getMapZoomPoints()
    },
    //获取视图四顶点
    map_drag() {
      //左下角坐标（西南方）
      let leftdown = []
      leftdown[0] = this.map.getBounds().getSouthWest().lng;
      leftdown[1] = this.map.getBounds().getSouthWest().lat;
      // console.log('左下方:' + leftdown);
      this.fourPosition.leftdown = leftdown;
      //右上角坐标（东北方向）
      let rightup = []
      rightup[0] = this.map.getBounds().getNorthEast().lng;
      rightup[1] = this.map.getBounds().getNorthEast().lat;
      // console.log('右上方:' + rightup);
      this.fourPosition.rightup = rightup;

      //var strText = "当前地图级别：" + zoom_val + " 左下角坐标：" + leftdown + " 右下角坐标：" + rightdown;
      //左上角：西北方
      let leftUp = []
      leftUp[0] = this.map.getBounds().getNorthWest().lng;
      leftUp[1] = this.map.getBounds().getNorthWest().lat;
      // console.log('左上方:' + leftUp);
      this.fourPosition.leftUp = leftUp;

      //右下角：东南方
      let rightdown = []
      rightdown[0] = this.map.getBounds().getSouthEast().lng;
      rightdown[1] = this.map.getBounds().getSouthEast().lat;
      // console.log('右下方:' + rightdown);
      this.fourPosition.rightdown = rightdown;
    },
    /* 鼠标键盘绑定事件 end */
    /* 请求数据事件 start */
    markPoint(node) {
      this.map_drag()
      this.getMapZoomPoints(node)
    },
    getMapZoomPoints() {
      //   console.log(this.rangeLevelPoints);
      let zoom = this.map.getZoom();
      let data = {
        label_name: '国家'
      }
      for (let key in this.rangeLevel) {
        if (this.rangeLevel[key].indexOf(zoom) > -1) {
          data.label_name = key;
        }
      }

      this.$store.dispatch("ajaxApi", {
        url: `/services/app-zonghe/api/knowledge/tongji?labels.equals=${data.label_name}&经度.greaterThan=${this.fourPosition.leftdown[0]}&经度.lessThan=${this.fourPosition.rightup[0]}&纬度.greaterThan=${this.fourPosition.leftdown[1]}&纬度.lessThan=${this.fourPosition.rightup[1]}&经度.valueType=double&纬度.valueType=double`,
        method: "get",
        succeed: (res) => {
          // console.log(res);
          this.nowZoom.level = zoom;
          this.nowZoom.type = data.label_name;
          res.statistics.forEach(tes => {
            // console.log(tes);
            let htmlStr =
              '<p class="map-circle-content"><span class="map-circle-name">' +
              tes['名称'] +
              '</span><span class="map-circle-count">' + tes
                .stat_model_count +
              '</span><p/>'
            let icon = L.divIcon({
              html: htmlStr,
              iconSize: [80, 80],
              className: 'map-circle'
            })
            let divlog = L.marker([tes['纬度'], tes['经度']], {
              icon: icon
            }).addTo(this.map).on('mouseover', function (event) {
              event.target.setZIndexOffset(1000)
            }).on('mouseout', function (event) {
              event.target.setZIndexOffset(300)
            });

            this.rangeLevelPoints[tes.id] = {};
            this.rangeLevelPoints[tes.id].point = divlog;
            this.rangeLevelPoints[tes.id].data = tes;
            this.rangeLevelPoints[tes.id].position = [];
            this.rangeLevelPoints[tes.id].position = [tes['纬度'], tes['经度']];
          })

          setTimeout(() => {
            this.$store.dispatch("ajaxApi", {
              url: `/services/app-zonghe/api/knowledge/tongji/relations?labels.equals=${data.label_name}&经度.greaterThan=${this.fourPosition.leftdown[0]}&经度.lessThan=${this.fourPosition.rightup[0]}&纬度.greaterThan=${this.fourPosition.leftdown[1]}&纬度.lessThan=${this.fourPosition.rightup[1]}&经度.valueType=double&纬度.valueType=double`,
              method: "get",
              succeed: (aes) => {
                var antPath = L.polyline.antPath;
                aes.statistics.forEach((yes) => {
                  if (this.rangeLevelPoints[yes
                    .start_node] == undefined &&
                    this
                      .rangeLevelPoints[yes.end_node] ==
                    undefined) {
                    return;
                  }
                  let longLatList = [this
                    .rangeLevelPoints[yes
                      .start_node].position, this
                        .rangeLevelPoints[yes.end_node]
                    .position
                  ];
                  let gPath = antPath(longLatList, {
                    "paused": false, //暂停  初始化状态
                    "reverse": false, //方向反转
                    "delay": 1000, //延迟，数值越大效果越缓慢
                    "dashArray": [10,
                      20
                    ], //间隔样式
                    "weight": 3, //线宽
                    "opacity": 0.8, //透明度
                    "color": "#FFF5EE", //颜色
                    "pulseColor": "#8B0000" //块颜色
                  });
                  gPath.addTo(this.map);
                  let central = gPath.getBounds()
                    .getCenter();
                  let mytext = L.divIcon({
                    html: yes.type,
                    className: 'my-div-text',
                    iconSize: 30
                  });
                  let textPoint = L.marker([central.lat,
                  central
                    .lng
                  ], {
                    icon: mytext
                  }).addTo(this.map);
                  let obj = {};
                  obj.text = textPoint;
                  obj.line = gPath;
                  this.tangelevelPath.push(obj)
                })
              }
            });
          }, 1000);
        },
        errored: (err) => {
          // console.log(err);
        }

      })
    }
    /* 请求数据事件 end */

  }
}
</script>

<style lang="less" scoped>
#gisMap {
  width: 100%;
  height: 100%;
  position: relative;
  .visual_control {
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 1000;
    width: 70px;
    padding: 5px 5px;
    display: flex;
    flex-flow: column nowrap;
  }
}
#map {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-circle {
  width: 100%;
  background-color: rgba(61, 150, 254, 0.8);
  border-radius: 50%;
  box-shadow: 0px 0px 5px #333;

  .map-circle-content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;

    .map-circle-name {
      display: inline-block;
      width: 80%;
      text-align: center;
    }

    .map-circle-count {
      font-size: 18px;
    }
  }
}

.map-circle:hover {
  background-color: rgba(255, 0, 0, 0.8);
}

.my-div-text {
  color: #fff;
  text-shadow: #000 1px 0 0, #000 0 1px 0, #000 -1px 0 0, #000 0 -1px 0;
  font-weight: bold;
  font-size: 18px;
}
</style>